<template>
  <el-dialog
    v-model="visible"
    :title="`${paramsProps.title}`"
    :destroy-on-close="true"
    width="60%"
    draggable
    append-to-body
    :close-on-press-escape="false"
    :close-on-click-modal="false"
  >
    <el-form
      ref="ruleFormRef"
      label-width="6.25rem"
      label-suffix=" :"
      :rules="rules"
      :model="paramsProps.row"
      @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="paramsProps.row.title" placeholder="请填写公告标题" clearable />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="公告类型" prop="type">
            <el-select v-model="paramsProps.row.type" clearable placeholder="请选择公告类型">
              <el-option
                v-for="item in optionsStore.getDictOptions('sys_message')"
                :key="item.id"
                :label="item.codeName"
                :value="item.id"
              />
            </el-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="发送对象" prop="sendType">
            <el-select v-model="paramsProps.row.sendType" clearable placeholder="请选择发送对象" @change="changeSendType">
              <el-option
                v-for="item in optionsStore.getDictOptions('sys_message_send_type')"
                :key="item.id"
                :label="item.codeName"
                :value="item.id"
              />
            </el-select> </el-form-item
        ></el-col>
      </el-row>

      <el-form-item label="选择用户" prop="userIds" v-if="isSendType == 1015002">
        <el-tag class="user-item" v-for="tag in users" :key="tag.id" type="info" closable @close="removeUser(tag.id)">
          {{ tag.nickname }}
        </el-tag>
        <el-button @click="chooseUser(paramsProps.row)"> 选择人员 </el-button>
      </el-form-item>
      <el-form-item label="部门" prop="deptIds" v-if="isSendType == 1015003">
        <el-tree-select
          v-model="paramsProps.row.deptIds"
          :data="parentMenus"
          check-strictly
          multiple
          placeholder="请选择部门"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="treeProps"
        />
      </el-form-item>
      <el-form-item label="公告内容" prop="content">
        <WangEditor v-model:value="paramsProps.row.content" height="25rem" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
  <MsgUserTransfer ref="MsgUserTransferRef" v-model="selectUserIds" />
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useOptionsStore } from '@/stores/modules/options';
import WangEditor from '@/components/WangEditor/index.vue';
import { getMenuTree } from '@/api/modules/system/dept';
import { bindUserDeptApi } from '@/api/modules/system/user';
import MsgUserTransfer from './MsgUserTransfer.vue';
import { getSysDeptLeaderApi } from '@/api/modules/system/dept';
defineOptions({
  name: 'MsgForm'
});
const optionsStore = useOptionsStore();
const visible = ref(false);
const paramsProps = ref({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined
});
const treeProps = {
  label: 'name',
  value: 'id'
};
const parentMenus = ref([]);
const rules = reactive({
  title: [{ required: true, message: '请填写公告标题' }],
  type: [{ required: true, message: '请选择公告类型' }],
  sendType: [{ required: true, message: '请选择发送对象' }],
  deptIds: [{ required: true, message: '请选择发送部门' }],
  content: [{ required: true, message: '请填写公告内容' }]
});
const isSendType = ref();
const MsgUserTransferRef = ref();
const allUser = ref([]);
const selectUserIds = ref([]);
const users = computed(() => {
  return allUser.value.filter(item => selectUserIds.value.includes(item.id));
});
const loadParentMenus = () => {
  getMenuTree({ excludeNodeId: paramsProps.value.row?.id }).then(res => {
    parentMenus.value = res.data;
  });
};
// 接收父组件传过来的参数
const acceptParams = params => {
  paramsProps.value = params;
  selectUserIds.value = paramsProps.value.row?.userIds || [];
  isSendType.value = params.row?.sendType;
  visible.value = true;
  loadLeaderInfo();
  loadParentMenus();
};

// 提交数据（新增/编辑）
const ruleFormRef = ref();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid: boolean) => {
    if (!valid) return;
    try {
      paramsProps.value.row.userIds = selectUserIds.value;
      await paramsProps.value.api!(paramsProps.value.row);
      ElMessage.success({ message: `${paramsProps.value.title}成功！` });
      paramsProps.value.getTableList!();
      visible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
const changeSendType = value => {
  isSendType.value = value;
  selectUserIds.value = [];
};
const loadLeaderInfo = () => {
  getSysDeptLeaderApi().then(res => {
    allUser.value = res.data.leaderInfoVOS;
  });
};
// 选择人员
const chooseUser = (row = {}) => {
  const params = {
    title: '指定用户',
    row: row,
    api: undefined,
    userList: allUser.value,
    selectIds: selectUserIds.value
  };
  MsgUserTransferRef.value?.acceptParams(params);
};

// 移除人员
const removeUser = (id: number) => {
  const index = selectUserIds.value.findIndex(item => item === id);
  if (index !== -1) {
    selectUserIds.value.splice(index, 1);
  }
};
defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.user-item {
  margin: 2px 5px;
}
</style>
